package com.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.entity.R;
import com.java.entity.SysMenu;
import com.java.entity.SysRoleMenu;
import com.java.service.SysMenuService;
import com.java.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

// 系统菜单Controller控制器
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    // 查询所有菜单树信息
    @RequestMapping("/list")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public R list() {
        List<SysMenu> menuList = sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num"));
        return R.ok().put("treeMenu", sysMenuService.buildTreeMenu(menuList));
    }

    // 添加或者修改
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add')" + "||" + "hasAuthority('system:menu:edit')")
    public R save(@RequestBody SysMenu sysMenu) {
        if (sysMenu.getId() == null || sysMenu.getId() == -1) {
            sysMenu.setCreateTime(new Date());
            sysMenuService.save(sysMenu);
        } else {
            sysMenu.setUpdateTime(new Date());
            sysMenuService.updateById(sysMenu);
        }
        return R.ok();
    }

    // 根据id查询
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
    public R findById(@PathVariable(value = "id") Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        return R.ok().put("sysMenu", sysMenu);
    }

    // 删除
    @Transactional
    @GetMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('system:menu:delete')")
    public R delete(@PathVariable(value = "id") Long id) {
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return R.error("请先删除子菜单！");
        }
        sysMenuService.removeById(id);
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("menu_id", id));
        return R.ok();
    }


}
